<template>
	<view class="inputAddress">
		<view class="wrapCalcHeight" style="width: 100%;" :style="'overflow-y:'+(showAddress==true?'hidden':'auto')">
			<view style="width: 100%;text-align: center;position: relative;">
				<!-- :style="'height:'+(showAddress==true?'230px':'100px')"  -->
				<map id="myMap" class="maMap" style="width: 100%;height: 280px;padding-top: 50px;" :latitude='latitude' :longitude='longitude'
					 :enable-scroll="enableScroll" :scale='scale' :markers='markers' :subkey="mapKey"
					 :show-location="true" @regionchange="getLatLong">
					<cover-image style="width: 50px;height: 50px;position: absolute;top: 32%;left: 44%;" src="https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/yaojike2020/cloudMedicine/ziyuan1.png" />
				</map>
				<view class="addressTitle" v-if="showAddress==true">
					<view @click="gotoChangeCity">{{city}}
						<u-icon style="margin-left: 16rpx;" color="#989797" name="arrow-down"></u-icon>
					</view>
					<u-search class="seachInput" v-model="seachKeywork" :show-action="false" placeholder-style="color:#d9d9d9"
							  placeholder="请输入收货地址" @change="inputKework" @focus="getFocus" @blur="loseFocus"></u-search>
				</view>

			</view>
			<view style="position: relative;transition: 0.8s;" :style="'top:'+(showAddress==true?'0px':'-155px')">
				<view class="changeAddress" >
					<view v-if="title&&address" style="display: flex;justify-content: space-between;">
						<view style="width: 70%;">
							<view class="title">{{title}}</view>
							<view class="addressCss">{{address}}</view>
						</view>
						<view @click="changeAddress()" style="line-height: 20px;height: 20px; padding: 6px;border: 1px solid #09C15F;border-radius: 6px;font-size: 14px;margin-top: 5px;margin-right: 10px;">修改地址</view>
					</view>
					<view @click="changeAddress()" v-else style="height: 30px;line-height: 30px;text-align: center;">选择收货地址</view>
					<!-- <image :style="'top:'+(id?'20px':'15px')" src="https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/yaojike2020/cloudMedicine/zhankai.png"></image> -->
				</view>
				<view v-show="showAddress" class="addressListHeight" style="width: 95%;">
					<!-- <view @click="showAddress=false" style="text-align: right;width: 100%;height: 40px;line-height: 40px;"><text style="border: 1px solid #B5B5B5;    border: 1px solid #B5B5B5;padding: 5px;border-radius: 5px;font-size: 15px;color: #383636;">收起列表</text></view> -->
					<view v-if="addressList !=''">
						<view v-for="(item,index) in addressList" :key="item.id" style="position: relative;width: 100%;text-align: left;border-bottom: 1px solid #e8e8e8;padding: 10px;color: #252426;">
							<view class="title">{{item.title}}</view>
							<view class="addressCss">{{item.address}}</view>
							<radio style="position: absolute;right: 30px;top: 20px;" :checked="item.checked" @click="selectOne(item)"></radio>
						</view>
						<view style="color: #d9d9d9;margin-top: 10px;margin-bottom: 30px;text-align: center;font-size: 14px;">没有找到更多相关位置了</view>
					</view>
				</view>
				<view v-if="showAddress==false">
					<ul style="margin: 10px;">
						<!-- <li>
						<view class="inputAddress-name">地区</view>
						<picker mode="region" :value="region" @change="regionChange" header-text="请选择所在地区" class="area_wrapper">
							<view class="picker" v-if="!regionChangeShow">
								{{region[0]}}{{region[1]}}{{region[2]}}
							</view>
							<view class="picker" v-if="regionChangeShow">
								{{region[0]}}{{region[1]}}{{region[2]}}
							</view>
						</picker>
					</li> -->
						<li>
							<view class="inputAddress-name">详细地址</view>
							<input class="inputAddress-input" style="" placeholder='请填写详细门牌号' v-model="add_detail" />
						</li>
						<li>
							<view class="inputAddress-name">收货人</view>
							<input class="inputAddress-input" placeholder='请填写收货人姓名' v-model="consignee" />
						</li>
						<li>
							<view class="inputAddress-name">手机</view>
							<input class="inputAddress-input" placeholder='请填写收货人手机号码' v-model="phone" />
						</li>
            <li>
              <view class="inputAddress-name">楼层</view>
              <input class="inputAddress-input" placeholder='如为配送地址时，请输入楼层高度' v-model="floor" />
            </li>
            <li style="display: flex;align-items: center;">
              <view class="inputAddress-name">有无电梯</view>
              <u-radio-group v-model="has_lift" @change="radioGroupChange">
                <u-radio
                    v-for="(item, index) in liftCheckList" :key="index"
                    :name="item.value"
                    :disabled="item.disabled"
                >
                  {{item.name}}
                </u-radio>
              </u-radio-group>
            </li>
						<li style="display: flex;align-items: center;">
							<view class="inputAddress-name">默认地址</view>
							<checkbox-group class="radio-group" style="padding-left: 20px;" @change="radioChange">
								<checkbox value="1" :checked="selectFlag" style="margin-left:10px;" />
							</checkbox-group>
						</li>
					</ul>
					<view style="text-align: center;display: flex;margin-top: 40px;">
						<button :disabled="submitBtnDisable" class="inputAddress-btnSave" style="left: 0;" :style="'width:'+(id==''?'90%':'40%')"
								@click="saveAddress">保存</button>
						<button :disabled="submitBtnDisable" class="inputAddress-btnDel" @click="delAddress" v-if="id!=''">删除</button>
					</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
import ssSelectCity from '@/components/ss-select-city/index.vue'
import UInput from "uview-ui/components/u-input/u-input";
export default {
	components: {
    UInput,
		ssSelectCity
	},

	data () {
		return {
      liftCheckList:[
          {
            name: '有',
            disabled:false,
            value:1,
          },
          {
            name: '无',
            disabled:false,
            value:0,
          }
      ],
			city:"",
			region: ["","",""],
			consignee:"",
			phone:"",
			add_detail:"",
			postcode:"",
      floor:"",
      has_lift:1,
			is_default:0,
			id:"",//如果是修改收货地址的时候，会传入一个id
			orderId:"",  //订单号
			// regionChangeShow: false,  //已废弃 显示三级联动

			showAddress:false,
			addressList:[],
			address:"",  //地址
			title:"",
			seachKeywork:"",  //搜索框的关键词
			focus:false, //搜索框是否获取到焦点
			// checked:false,
			clickAddressaKeywork:"",
			qqmapsdk:"",
			MapContext:"", // 地图上下文
			latitude: 23.114509,
			longitude: 113.403536,
			scale:16,
			markers: [],
			submitBtnDisable: false,
			enableScroll:false, //是否允许拖动选址
			address_info: '',
			mapKey:"" //地图的key
		}
	},
	computed: {
		selectFlag(){
			if(this.is_default==0){
				return false
			}else{
				return true
			}
		}
	},
	watch:{
		//如果展开
		showAddress(newVal){
			if(newVal==true){
				this.enableScroll = true
			}else{
				this.enableScroll = false
			}
		}
	},
	async onLoad(options){
		this.initMap()
		//如果是修改收货地址的时候，会传入一个id
		if(options.id){
			this.id=options.id
			await this.getAddressDetails(options.id)
		}else{
			this.id=''
			this.consignee=''
			this.phone=''
			this.add_detail=''
			this.postcode=''
			this.is_default=''
			this.region=["","",""]
			//如果上次选过别的城市，存到本地，查看本地有，就获取上次的城市，没有就获取当前定位门店的位置
			if(wx.getStorageSync('city')){
				this.city=wx.getStorageSync('city')
				this.geocoder(this.city) //根据城市名称获取经纬度
			}else{
				//获取定位信息(防止人在深圳定了位，但他去广州了，位置还是深圳的经纬度)
				await this.getLocationInfo()
				// if(wx.getStorageSync("latitude") && wx.getStorageSync("longitude")){
				//  console.log(666)
				//  this.latitude = wx.getStorageSync("latitude")
				//  this.longitude = wx.getStorageSync("longitude")
				// }
				this.reverseAddress()
			}
			// this.createdMarker()  //创建小标杆
			// this.markers[0].latitude = this.latitude
			// this.markers[0].longitude = this.longitude
		}
		this.orderId=options.orderId
	},
	onShow(){
		if(wx.getStorageSync('city')){
			this.geocoder(wx.getStorageSync('city'))
		}
	},
	onUnload() {
		wx.removeStorageSync("city")
	},
	methods:{
    radioGroupChange(e){
      // console.log(e)
      this.has_lift=e;
    },
		//通过微信获取经纬度
		async getLocationInfo() {
			let _this = this;
			await wx.getLocation({
				type: 'gcj02',
				success(res) {
					wx.setStorageSync("latitude",res.latitude)
					wx.setStorageSync("longitude",res.longitude)
					_this.latitude = wx.getStorageSync("latitude")
					_this.longitude = wx.getStorageSync("longitude")
				},
				fail(err){
					wx.getSetting({
						success: (res) => {
							if (!res.authSetting['scope.userLocation']) {
								//打开提示框，提示前往设置页面
								_this.layerModel = true;
							} else{
								wx.showToast({
									title: '请检查手机位置服务是否打开',
									icon: 'none'
								})
							}
						}
					})
				}
			})
		},

		//解除禁用提交按钮
		enableSubmitBtn() {
			this.submitBtnDisable = false
		},

		//禁用提交按钮
		disableSubmitBtn() {
			this.submitBtnDisable = true
		},

		//根据城市名称获取经纬度
		async geocoder(keyword){
			// 调用接口
			await this.qqmapsdk.geocoder({
				//获取表单传入地址
				address: keyword, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
				success:(res)=> {//成功后的回调
					var item = res.result
					let stringCity = item.address_components.city.replace("市",'')
					this.city = stringCity
					//所在位置
					this.latitude = item.location.lat
					this.longitude = item.location.lng
					//给小标杆赋值坐标
					// this.markers[0].latitude = item.location.lat
					// this.markers[0].longitude = item.location.lng
					this.seachAddress(this.city)
				},
				fail: function(error) {
					console.error(error);
				},
			})
		},
		//去选择城市
		gotoChangeCity(){
			wx.navigateTo({
				url:"changeCity?city="+this.city
			})
		},
		//点击选择收货地址 展开/隐藏
		changeAddress(){
			this.showAddress=!this.showAddress
		},
		//选择地址列表的一个地址时触发
		selectOne(item){
			this.addressList.forEach(addressItem=>{
				if(item.id == addressItem.id){
					addressItem.checked = true
					if(addressItem.checked==true){
						this.address=item.address
						this.title = item.title
						//所在位置
						this.latitude = item.location.lat
						this.longitude = item.location.lng
						//给小标杆赋值坐标
						// this.markers[0].latitude = item.location.lat
						// this.markers[0].longitude = item.location.lng
						//填充省市区
						this.region = [item.ad_info.province,item.ad_info.city,item.ad_info.district]
						this.add_detail = item.title
						this.address_info = item.address
					}
				}else{
					addressItem.checked = false
				}

			})

			//显示地址列表模态款
			this.showAddress = false
		},
		//搜索框获取焦点
		getFocus(){
			this.focus = true
		},
		//搜索框失去焦点
		loseFocus(){
			this.focus = false
		},
		//监听地址输入框，输入框发生变化触发
		inputKework(){
			if(this.focus==true){
				this.seachAddress(this.seachKeywork) //搜索目标地址
				this.showAddress=true
			}else{
				return false
			}

		},
		//拖动地图获取经纬度，并搜出位置
		getLatLong(e){
			//获取当前地图中心的经纬度
			//只为拖动才触发
			if(e.type=='end' && e.causedBy == 'drag'){
				this.MapContext.getCenterLocation({
					type: 'gcj02',
					success: (res) => {
						this.latitude=res.latitude,
								this.longitude= res.longitude
						this.reverseAddress()

						//maker小标点移动动画
						// this.MapContext.translateMarker({
						// 	markerId:this.markers[0].id,
						// 	autoRotate:false,
						// 	rotate:0,
						// 	duration:100,
						// 	destination:{
						// 		latitude:res.latitude,
						// 		longitude:res.longitude
						// 	},
						// 	animationEnd(){
						// 		console.log("动画结束")
						// 	}
						// })
					}
				})
			}

		},
		//逆地址解析 通过经纬度查询出当前地址
		reverseAddress(){
			this.qqmapsdk.reverseGeocoder({
				location: this.latitude+','+this.longitude,
				poi_options:"radius=5;policy=2",
				success:(res)=>{
					let stringCity = res.result.address_component.city.replace("市",'')
					this.city = stringCity
					if(this.id){
						this.address = res.result.address
						this.title = res.result.formatted_addresses.recommend
					}
					this.seachAddress(res.result.formatted_addresses.recommend)
				}
			})
		},
		//搜索附近地址
		seachAddress(keyword){
			// 调用接口
			this.qqmapsdk.search({
				keyword: keyword,  //搜索关键词
				location: this.latitude+','+this.longitude,  //设置周边搜索中心点（不能注释掉，换城市搜索需要用到）
				success:(res)=>{ //搜索成功后的回调
					res.data.forEach(item=>{
						item.checked = false
					})
					this.addressList = res.data

					//多个标记点
					// var mks = []
					// for (var i = 0; i < res.data.length; i++) {
					//   mks.push({ // 获取返回结果，放到mks数组中
					//     title: res.data[i].title,
					//     id: res.data[i].id,
					//     latitude: res.data[i].location.lat,
					//     longitude: res.data[i].location.lng,
					//     iconPath:"https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/yaojike2020/cloudMedicine/ziyuan1.png", //图标路径
					//     width: 20,
					//     height: 20
					//   })
					// }
					//   this.markers=mks
				},
				fail: function (res) {
					console.log(res);
				},

			});
		},
		//初始化创建地图
		initMap(){
			this.mapKey = wx.getStorageSync("mapKey")
			var QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');
			this.qqmapsdk = new QQMapWX({
				key:  this.mapKey
			});
			this.MapContext = wx.createMapContext("myMap")

		},
		// createdMarker(){
		//  //创建个小标点
		//  let marker = {
		//   id:1,
		//   iconPath:"https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/yaojike2020/cloudMedicine/ziyuan1.png",
		//   latitude: this.latitude,
		//   longitude: this.longitude,
		//   width:30,
		//   height:30
		//  }
		//  this.markers.push(marker)
		//  this.reverseAddress("detail")
		// },
		radioChange(e){
			this.is_default=e.target.value[0]
		},
		// regionChange(e){
		//   this.region=e.target.value;
		//   this.regionChangeShow = true;
		// },
		async delAddress(){
			wx.showLoading({
				title: '删除中'
			})
			this.disableSubmitBtn()
			var userToken=wx.getStorageSync('userToken')
			let res=await this.$api.deleteShippingAddress({id:this.id,user_token:userToken},this.$baseUrl)
			wx.hideLoading()
			if(res.data.level=='success'){
				uni.showToast({
					icon: 'success',
					title: res.data.message,
					duration: 1500
				})
			} else{
				this.enableSubmitBtn()
				uni.showToast({
					icon: 'none',
					title: res.data.message,
					duration: 1500
				})
			}
			setTimeout(()=>{
				if(res.data.level=='success'){
					wx.navigateBack({delta:1})
				}
			},1500)
		},
		async saveAddress(){
			if(!this.latitude || !this.longitude || !this.address || !this.title){
				uni.showToast({
					icon: 'success',
					title: "请选择收货地址",
					duration: 1500,
					icon:"none"
				})
				return false
			}
			this.disableSubmitBtn()
			wx.showLoading({
				title: '保存中'
			})
			var userToken=wx.getStorageSync('userToken')
			let params={
				user_token:userToken,
				consignee:this.consignee,
				phone:this.phone,
				province:this.region[0],
				city:this.region[1],
				area:this.region[2],
				address:this.add_detail,
				postcode:this.postcode,
				is_default:this.is_default,
				id:this.id,
				lat:this.latitude,
				lng:this.longitude,
				address_info: this.address_info,
        has_lift:this.has_lift,
        floor:this.floor
			}
			let res=await this.$api.newShippingAddress(params,this.$baseUrl)
			wx.hideLoading()
			if(res.data.level=='success'){
				uni.showToast({
					icon: 'success',
					title: res.data.message,
					duration: 1500
				})
			} else{
				this.enableSubmitBtn()
				uni.showToast({
					icon: 'none',
					title: res.data.message,
					duration: 1500
				})
			}
			setTimeout(()=>{
				if(res.data.level=='success'){
					wx.navigateBack({delta:1})
				}
			},1500)

		},
		async getAddressDetails(id){

			var userToken=wx.getStorageSync('userToken')
			let res=await this.$api.getShippingAddress({user_token:userToken,id:id},this.$baseUrl)
			let data=res.data.data
			this.consignee=data.consignee
			this.phone=data.phone
			this.add_detail=data.address
			this.postcode=data.postcode
			this.is_default=data.is_default
			this.region[0]=data.province
			this.region[1]=data.city
			this.region[2]=data.area
      this.floor=data.floor
      this.has_lift=data.has_lift
			//如果之前有设地址，有经纬度赋值。否则取本地的经纬度获取当前位置
			if(data.lat!=0 && data.lng!=0){
				this.latitude = data.lat
				this.longitude = data.lng
				// this.markers[0].latitude = data.lat
				// this.markers[0].longitude = data.lng
			}else{
				this.latitude = wx.getStorageSync("latitude")
				this.longitude = wx.getStorageSync("longitude")
				// this.markers[0].latitude = this.latitude
				// this.markers[0].longitude = this.longitude
			}
			// this.createdMarker()
			this.reverseAddress()

		}
	},

}
</script>

<style scoped lang="scss" type="text/css">
	.addressListHeight {
		height: calc(100vh - 395px);
		margin: 10px;
		background: #fff;
		border-radius: 7px;
		overflow-y: auto;
		overflow-x: hidden;
	// width: 95%;position: absolute;left: 10px;margin-top: -9px;background-color: #f7f7f7;z-index: 10;
	}

	.wrapCalcHeight {
	// height: calc(100vh - 60px);
		height: 100vh;
		overflow-y: auto;
		overflow-x: hidden;
	}

	.addressTitle {
		width: 100%;
		position: absolute;
		top: 0px;
		display: flex;
		background: #fff;
		height: 35px;
		line-height: 35px;
		padding: 10px;

	// .dropIcon {
	   // 	display: inline-block;
	   // 	width: 8px;
	   // 	height: 8px;
	   // 	border: 2px solid #989797;
	   // 	border-top: none;
	   // 	border-left: none;
	   // 	transform: rotate(45deg);
	   // 	margin-left: 7px;
	   // }
	}

	.seachInput {

	// border: 1px solid #dadada;
	// background: #fff;
		height: 35px;
		line-height: 35px;
		border-radius: 5px;
		font-size: 14px;
		margin-left: 10px;
		width: 75%;
	}

	.picker {
		text-indent: 20px;
	}

	.changeAddress {
		margin: 10px;
		border: 1px solid #ececec;
		background-color: #fff;
		border-radius: 5px;
		color: #2CB85F;
		padding: 10px;
		position: relative;
		text-align: left;

	image {
		width: 25px;
		height: 25px;
		vertical-align: middle;
		position: absolute;
		right: 15px;
		top: 20px;
	}
	}

	.title {
		width: 95%;
		font-size: 14px;
		color: #333333;
		white-space: nowrap;  //不换行
	overflow: hidden; //超出隐藏
	text-overflow: ellipsis;  //文本超出，用ellipsis省略号
	}

	.addressCss {
		width: 95%;
		font-size: 14px;
		margin-top: 5px;
		color: #BFBFBF;
		white-space: nowrap;  //不换行
	overflow: hidden; //超出隐藏
	text-overflow: ellipsis;  //文本超出，用ellipsis省略号
	}

	@import "../../common/css/mixin.scss";

	.inputAddress {
		width: 100%;
		height: 100vh;
		overflow: hidden;
		background: #f5f5f5;

	.inputAddress-name {
		width: 80px;
	}

	li {
		display: flex;
		height: 50px;
		background-color: #fff;
		border-top: 1px solid #eee;
		color: black;

	.area_wrapper {
		width: calc(100% - 90px);
		height: 100%;

	view {
		margin: 10px 10px;
		height: 30px;
		line-height: 30px;
		width: calc(100% - 20px);
	@include ellipsis(1);
	}
	}
	}

	&-name {
		 width: 70px;
		 line-height: 50px;
		 text-indent: 10px;
	 // color:white;
	 }

	&-input {
		 flex: 1;
		 height: 30px;
		 margin: 10px 10px;
		 line-height: 30px;
		 padding-left: 20px;
	 }

	.inputAddress-btnSave {
		width: 40%;
		line-height: 40px;
		background-color: #2CB85F;
		border-radius: 3px;
		text-align: center;
		color: #fff;
		margin: 0px 5% 0px;
	// position: absolute;
		bottom: 10px;
		border-radius: 25px;
	// left: 0;
	}

	&-btnDel {
	 @extend .inputAddress-btnSave;
		 background-color: #ff3236 !important;
		 color: #FFFFFF;
		 margin: 0px 5% 0px !important;
		 right: 0 !important;
	 }
	}
</style>
